package com.resou.reader.mine.login;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.aigestudio.wheelpicker.WheelPicker;
import com.resou.reader.R;
import com.resou.reader.api.ApiImp;
import com.resou.reader.api.entry.BookDetailBean;
import com.resou.reader.api.entry.Result;
import com.resou.reader.api.service.UserService;
import com.resou.reader.base.v.BaseActivity;
import com.resou.reader.commom.Constant;
import com.resou.reader.setting.GlobalSettingManager;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.utils.ConstellationUtils;
import com.resou.reader.utils.DateUtils;
import com.resou.reader.utils.ToastUtil;
import com.resou.reader.utils.log.DLog;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class BirthdayActivity extends BaseActivity {
    private static final String TAG = "BirthdayActivity";
    @BindView(R.id.radio_group)
    RadioGroup mRadioGroup;
    @BindView(R.id.constellation_text)
    TextView mConstellationTv;
    @BindView(R.id.birthday_text)
    TextView birthdayTv;
    @BindView(R.id.year_wheel)
    WheelPicker mYearPicker;
    @BindView(R.id.month_wheel)
    WheelPicker mMonthPicker;
    @BindView(R.id.day_wheel)
    WheelPicker mDayPicker;

    private int mYear;
    private int mMonth;
    private int mDay;
    String brithday = "";
    String constellation = "";
    final List<String> years = new ArrayList<>();
    final List<String> months = new ArrayList<>();
    final List<String> days = new ArrayList<>();
    private UserService mService;

    @Override
    public int getLayoutId() {
        return R.layout.activity_birthday;
    }

    @Override
    protected void initPresenter() {

    }

    @OnClick({R.id.complete_text})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.complete_text:
                checkBirthdayStatus();
//                updateBirthday(mYear + "-" + mMonth + "-" + mDay);
                break;
        }
    }

    @Override
    protected void initView() {
        mService = ApiImp.getInstance().getService(UserService.class);
        boolean isPublicityBirthday = GlobalSettingManager.settingManager().getPublicityBirthday(this);
        if (isPublicityBirthday)
            mRadioGroup.check(R.id.publicity);
        else
            mRadioGroup.check(R.id.privacy);
        mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.publicity:
                        GlobalSettingManager.settingManager().setPublicityBirthday(BirthdayActivity.this, true);
                        break;
                    case R.id.privacy:
                        GlobalSettingManager.settingManager().setPublicityBirthday(BirthdayActivity.this, false);
                        break;
                }
            }
        });

        final int year = DateUtils.getCurrentYear() - 1;
        Log.d("BirthdayActivity", "year == " + year);
        for (int i = year - 100; i <= year; i++) {
            years.add(i + "年");
        }
        for (int i = 1; i < 13; i++) {
            months.add(i + "月");
        }
        resetDayData(31);

        mYearPicker.setData(years);
        mMonthPicker.setData(months);
        mDayPicker.setData(days);

        String birthday = getIntent().getStringExtra("brithday");
//        if (TextUtils.isEmpty(birthday)) {
//            birthday = "1990-01-01";
//        }
        if (TextUtils.isEmpty(birthday)) {
            mYear = year - 20;
            mMonth = 1;
            mDay = 1;
        } else {
            String[] sub = birthday.split("-");
            mYear = Integer.parseInt(sub[0].trim());
            mMonth = Integer.parseInt(sub[1].trim());
            mDay = Integer.parseInt(sub[2].trim());
            brithday = birthday;
        }
        birthdayTv.setText(String.valueOf(brithday));
        int yearIndex = years.indexOf(mYear + "年");
        int monthIndex = months.indexOf(mMonth + "月");
        int dayIndex = days.indexOf(mDay + "日");
        mYearPicker.setSelectedItemPosition(yearIndex);
        mMonthPicker.setSelectedItemPosition(monthIndex);
        mDayPicker.setSelectedItemPosition(dayIndex);

        constellation = ConstellationUtils.queryConstellation(mMonth, mDay);
        mConstellationTv.setText(constellation);

        mYearPicker.setOnItemSelectedListener(new WheelPicker.OnItemSelectedListener() {
            @Override
            public void onItemSelected(WheelPicker picker, Object data, int position) {
                mYear = year + position - years.size() + 1;
                brithday = mYear + "-" + mMonth + "-" + mDay;
                birthdayTv.setText(String.valueOf(brithday));
                Log.d("BirthdayActivity", "mYear : " + mYear);

            }
        });

        mMonthPicker.setOnItemSelectedListener(new WheelPicker.OnItemSelectedListener() {
            @Override
            public void onItemSelected(WheelPicker picker, Object data, int position) {
                mMonth = position + 1;
                constellation = ConstellationUtils.queryConstellation(mMonth, mDay);
                mConstellationTv.setText(constellation);
                brithday = mYear + "-" + mMonth + "-" + mDay;
                birthdayTv.setText(String.valueOf(brithday));
                Log.i(TAG, "onItemSelected: mMonth" + String.valueOf(brithday));

                switch (mMonth) {
                    case 1:
                    case 3:
                    case 5:
                    case 7:
                    case 8:
                    case 10:
                    case 12:
                        resetDayData(31);
                        break;
                    case 4:
                    case 6:
                    case 9:
                    case 11:
                        resetDayData(30);
                        break;
                    case 2:
                        if (mYear % 4 == 0) {
                            resetDayData(29);
                        } else {
                            resetDayData(28);
                        }
                        break;
                }
            }
        });

        mDayPicker.setOnItemSelectedListener(new WheelPicker.OnItemSelectedListener() {
            @Override
            public void onItemSelected(WheelPicker picker, Object data, int position) {
                mDay = position + 1;
                constellation = ConstellationUtils.queryConstellation(mMonth, mDay);
                mConstellationTv.setText(constellation);
                brithday = mYear + "-" + mMonth + "-" + mDay;
                birthdayTv.setText(String.valueOf(brithday));
                Log.i(TAG, "onItemSelected: day" + String.valueOf(brithday));

            }
        });
    }

    @Override
    protected void retryRefreshData() {

    }

    private void resetDayData(int num) {
        if (days.size() == num) {
            return;
        }
        days.clear();
        for (int i = 1; i <= num; i++) {
            days.add(i + "日");
        }
        mDayPicker.setData(days);
//        mDayPicker.requestLayout();
    }

    public static void startActivity(Context context, String brithday) {
        Intent intent = new Intent(context, BirthdayActivity.class);
        intent.putExtra("brithday", brithday);
        ((Activity) context).startActivityForResult(intent, Constant.REQUEST_BIRTHDAY);
    }

    @Override
    public Context getViewContext() {
        return this;
    }

    @Override
    protected void onDestroy() {
        mYearPicker.setOnItemSelectedListener(null);
        mMonthPicker.setOnItemSelectedListener(null);
        mDayPicker.setOnItemSelectedListener(null);
        mYearPicker = null;
        mMonthPicker = null;
        mDayPicker = null;
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
//        Intent intent = new Intent();
//        intent.putExtra("birthday", mYear + "-" + mMonth + "-" + mDay);
//        intent.putExtra("constellation", mConstellationTv.getText().toString());
//        setResult(RESULT_OK, intent);
        super.onBackPressed();
    }


    /**
     * 更新生日
     *
     * @param birthday
     */
    public void updateBirthday(final String birthday) {
        mService.updateBirthday(UserInstance.getToken(), birthday).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Result>() {
                    @Override
                    public void accept(Result result) throws Exception {
                        int code = result.getCode();
                        if (code == 0) {
                            Intent intent = new Intent();
                            intent.putExtra("birthday", brithday);
                            intent.putExtra("constellation", constellation);
                            setResult(RESULT_OK, intent);
                            finish();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                        ToastUtil.makeShortToast("网络异常");
                    }
                });
    }

    /**
     * 检测用户是否设置过生日
     */
    public void checkBirthdayStatus() {
        mService.checkBirthdayState(UserInstance.getToken()).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Result>() {
                    @Override
                    public void accept(Result result) throws Exception {
                        int code = result.getCode();
                        if (code == 0) {
                            initDialog(code, result.getMsg() + "");
                        } else if (code == 99) {
                            initDialog(code, result.getMsg() + "");
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                        ToastUtil.makeShortToast("网络异常");
                    }
                });
    }


    /**
     * 设置生日弹框
     *
     * @param content 描述
     */
    private void initDialog(int code, String content) {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_birthday, null);
        TextView tvCancel = view.findViewById(R.id.tvCancel);
        TextView tvContent = view.findViewById(R.id.tvContent);
        TextView tvBirthday = view.findViewById(R.id.tvBirthday);
        if (code == 99) {
            tvContent.setText("您的生日一旦设置不可更改哦");
            tvBirthday.setText("生日：" + brithday);
        } else {
            tvContent.setText("生日仅可设置一次,您已设置过生日哦");
            tvBirthday.setText("生日：" + brithday);
        }
        TextView tvOk = view.findViewById(R.id.tvOk);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(view);
        AlertDialog alertDialog = builder.create();
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (alertDialog.isShowing()) {
                    alertDialog.dismiss();
                    if (code == 99) {
                        updateBirthday(brithday);
                    } else {
                        finish();
                    }
                }
            }
        });
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (alertDialog.isShowing()) {
                    alertDialog.dismiss();
                }
            }
        });
        alertDialog.show();
    }
}
